package m202401.d12;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/1/12 10:03
 */
//112. 路径总和
public class Q112 {

    boolean flag = false;

    public boolean hasPathSum(TreeNode root, int targetSum) {
        flag = false;
        travel(root, 0, targetSum);
        return flag;
    }

    public void travel(TreeNode node, int sum, int targetSum) {
        if (flag) {
            return;
        }
        if (isLeaf(node)) {
            flag = (sum + node.val) == targetSum;
            return;
        }
        if (node == null) {
            return;
        }
        travel(node.left, sum + node.val, targetSum);
        travel(node.right, sum + node.val, targetSum);
    }

    private boolean isLeaf(TreeNode node) {
        return node != null && node.left == null && node.right == null;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
